package com.zlll.winner.service.lhtUser.async;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zlll.winner.business.model.lhtUser.LhtUser;
import com.zlll.winner.mapper.lhtUser.LhtUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Async
@Slf4j
public class LhtUserAsyncService {

    @Resource
    private LhtUserMapper userMapper;

    /**
     * 增加积分
     *
     * @param userId
     * @param integral
     * @return
     */
    public int addIntegral(Long userId, Integer integral) {
        Long time = System.currentTimeMillis();

        LhtUser lhtUser = userMapper.selectById(userId);
        Long oleUpdateTime = lhtUser.getUpdateTime();

        lhtUser.setTotalIntegral(lhtUser.getTotalIntegral() + integral);
        lhtUser.setResidueIntegral(lhtUser.getResidueIntegral()+integral);
        lhtUser.setUpdateTime(time);


        int update = userMapper.update(lhtUser, Wrappers.<LhtUser>lambdaQuery()
                .eq(LhtUser::getId, userId)
                .eq(LhtUser::getUpdateTime, oleUpdateTime));

        return update;
    }

    @Async
    public void changeIntegral(Long userId, Integer integral) throws InterruptedException {
        int res = 0;
        int sum = 10;
        while (res == 0 && sum > 0) {
            res = addIntegral(userId, integral);
            if (res == 0) Thread.sleep(500L);
            sum--;
        }
        log.error("增加完毕。");
    }


    /**
     * 减少积分
     *
     * @param userId
     * @param integral
     * @return
     */
    public int subtractIntegral(Long userId, Integer integral) {
        Long time = System.currentTimeMillis();
        LhtUser lhtUser = userMapper.selectById(userId);
        Long oleUpdateTime = lhtUser.getUpdateTime();
//        lhtUser.setTotalIntegral(lhtUser.getTotalIntegral() + integral);
        lhtUser.setResidueIntegral(lhtUser.getResidueIntegral()-integral);
        lhtUser.setUpdateTime(time);


        int update = userMapper.update(lhtUser, Wrappers.<LhtUser>lambdaQuery()
                .eq(LhtUser::getId, userId)
                .eq(LhtUser::getUpdateTime, oleUpdateTime));

        return update;
    }

    @Async
    public void changeSubtractIntegral(Long userId, Integer integral) throws InterruptedException {
        int res = 0;
        int sum = 10;
        while (res == 0 && sum > 0) {
            res = subtractIntegral(userId, integral);
            if (res == 0) Thread.sleep(500L);
            sum--;
        }
        log.error("增加完毕。");
    }

}
